package com.song.algorithm.blockchain;

import java.util.Date;

/**
 * @desc:
 * @author: WUSONG
 * @date: 2018/10/24 0024上午 10:01
 */
public class Block {

    private String hash;//存放数字签名

    private String preHash;//上一个块的签名

    private String data;

    private long timestamp;

    private int nonce;

    public Block(String hash, String preHash) {
        this.hash = hash;
        this.preHash = preHash;
        this.timestamp = new Date().getTime();
        this.hash = calculateHash();
    }


    public String calculateHash() {
        String calculatedhash = SHA256Utils.applySha256(preHash + Long.toString(timestamp) +Integer.toString(nonce)+ data);
        return calculatedhash;
    }

    public void mineBlock(int difficulty) {
        String target = new String(new char[difficulty]).replace('\0', '0');
        while (!hash.substring(0, difficulty).equals(target)) {
            nonce++;
            hash = calculateHash();
        }
        System.out.println("Block Mined!!!" + hash);
    }

    public String getHash() {
        return hash;
    }

    public String getPreHash() {
        return preHash;
    }

    public String getData() {
        return data;
    }

    public long getTimestamp() {
        return timestamp;
    }
}
